package com.example.course.controller;

import com.example.course.dto.TopicDTO;
import com.example.course.service.TopicService;
import com.example.course.tool.R;
import com.example.course.vo.TopicVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 题库控制器
 *
 * @author Jasmine-drs
 * @date 2025-04-22
 */
@RestController
@RequestMapping("/api/topic")
@Api(tags = "题库接口")
public class TopicController {

	private final TopicService topicService;

	public TopicController(TopicService topicService) {
		this.topicService = topicService;
	}

	@PostMapping
	@ApiOperation("添加题目（仅教师）")
	public R<TopicVO> addTopic(
			@ApiParam(value = "题目信息", required = true) @Valid @RequestBody TopicDTO topicDTO,
			@ApiParam(value = "用户角色", required = true) @RequestParam boolean isTeacher) {
		try {
			TopicVO topicVO = topicService.addTopic(topicDTO, isTeacher);
			return R.success(topicVO);
		} catch (Exception e) {
			return R.err("添加题目失败：" + e.getMessage());
		}
	}

	@DeleteMapping("/{id}")
	@ApiOperation("删除题目（仅教师）")
	public R<Boolean> deleteTopic(
			@ApiParam(value = "题目ID", required = true) @PathVariable Integer id,
			@ApiParam(value = "用户角色", required = true) @RequestParam boolean isTeacher) {
		try {
			boolean success = topicService.deleteTopic(id, isTeacher);
			if (success) {
				return R.success(true);
			} else {
				return R.err("删除题目失败，题目可能不存在");
			}
		} catch (Exception e) {
			return R.err("删除题目失败：" + e.getMessage());
		}
	}

	@GetMapping("/list")
	@ApiOperation("获取题目列表")
	public R<List<TopicVO>> getTopicList() {
		try {
			List<TopicVO> topicVOList = topicService.getTopicList();
			return R.success(topicVOList);
		} catch (Exception e) {
			return R.err("获取题目列表失败：" + e.getMessage());
		}
	}

	@GetMapping("/{id}")
	@ApiOperation("根据ID获取题目")
	public R<TopicVO> getTopicById(
			@ApiParam(value = "题目ID", required = true) @PathVariable Integer id) {
		try {
			TopicVO topicVO = topicService.getTopicById(id);
			if (topicVO != null) {
				return R.success(topicVO);
			} else {
				return R.err("题目不存在");
			}
		} catch (Exception e) {
			return R.err("获取题目失败：" + e.getMessage());
		}
	}
} 